package cloud.seata.account.service;

import cloud.seata.account.repository.AccountRepository;
import cloud.seata.account.repository.entity.Account;
import cloud.seata.api.TccAccountService;
import org.apache.dubbo.config.annotation.DubboService;
import org.apache.seata.rm.tcc.api.BusinessActionContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;

@DubboService
@Service
public class AccountServiceImpl implements TccAccountService {

    @Autowired
    private AccountRepository accountRepository;

    @Override
    public boolean prepare(BusinessActionContext actionContext) {
        Account account = accountRepository.selectById(1);


        Account a = new Account();

        a.setId(1);
        a.setWallet(account.getWallet().subtract(BigDecimal.valueOf(500)));
        a.setFrozen(account.getFrozen().add(BigDecimal.valueOf(500)));
        accountRepository.updateById(a);

        return true;
    }

    @Override
    public boolean commit(BusinessActionContext actionContext) {

        Account account = accountRepository.selectById(1);

        System.out.println("Acount 成功");
        account.setFrozen(account.getFrozen().subtract(BigDecimal.valueOf(500)));
        accountRepository.updateById(account);

        return true;
    }

    @Override
    public boolean rollback(BusinessActionContext actionContext) {
        Account account = accountRepository.selectById(1);
        System.out.println("看看没有回滚的TCC");
        System.out.println(account.getFrozen().subtract(BigDecimal.valueOf(500)));
        System.out.println(account.getWallet().add(BigDecimal.valueOf(500)));
        account.setFrozen(account.getFrozen().subtract(BigDecimal.valueOf(500)));
        account.setWallet(account.getWallet().add(BigDecimal.valueOf(500)));
        accountRepository.updateById(account);
        return true;
    }
}
